package com.cts.tmall.biz.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cts.tmall.com.exception.SystemException;
import com.cts.tmall.com.message.RspCode;
import com.cts.tmall.dal.entity.TmallPrd;
import com.cts.tmall.dal.entity.TmallTimingSale;
import com.cts.tmall.dal.mapper.TmallPrdMapper;
import com.cts.tmall.dal.mapper.TmallTimingSaleMapper;
import com.google.common.collect.ImmutableMap;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class TimingSaleService {

    @Autowired
    private TmallTimingSaleMapper timingSaleMapper;
    @Autowired
    private TmallPrdMapper prdMapper;


    public Map<String, Object> queryTimingSale(Long createUserId,String prdNo, String prdName, Date saleStartTime,
                                               Date saleEndTime, Long pageNumb, Long pageSize) {
        IPage<TmallTimingSale> page = timingSaleMapper.queryTimingSale(new Page<TmallTimingSale>(pageNumb, pageSize), prdNo, prdName, saleStartTime, saleEndTime, createUserId);
        List<ImmutableMap<String, Object>> data = page.getRecords().stream().map(timingSale -> {
            TmallPrd prd = prdMapper.selectById(timingSale.getPrdNo());
            return ImmutableMap.<String, Object>builder()
                    .put("id", timingSale.getId())
                    .put("saleTime", timingSale.getSaleTime())
                    .put("prdInfo", prd == null ? new HashMap<>() : prd)
                    .build();
        }).collect(Collectors.toList());
        return ImmutableMap.<String, Object>builder()
                .put("total", page.getTotal())
                .put("pageNumb", page.getCurrent())
                .put("pageSize", page.getSize())
                .put("data", data)
                .build();
    }

    public TmallTimingSale addTimingSale(TmallTimingSale timingSale) {
        if (timingSale.getPrdNo() == null) {
            log.error("商品ID为空！");
            throw new SystemException(RspCode.FAILURE_PARAMS, "商品ID为空！");
        }
        if (timingSale.getSaleTime() == null) {
            log.error("开售时间为空！");
            throw new SystemException(RspCode.FAILURE_PARAMS, "开售时间为空！");
        }
        timingSaleMapper.insert(timingSale);
        return timingSaleMapper.selectById(timingSale.getId());
    }

    public TmallTimingSale updTimingSale(TmallTimingSale timingSale) {
        if (timingSale.getId() == null) {
            log.error("主键为空！");
            throw new SystemException(RspCode.FAILURE_PARAMS, "主键为空！");
        }
        timingSaleMapper.updateById(timingSale);
        return timingSaleMapper.selectById(timingSale.getId());
    }
}
